package com.candy.control;

import com.candy.service.LoginService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
//        获取初始化参数
        String initValue=config.getInitParameter("init");
        System.out.println("获取初始化参数initParam:"+initValue);
//        获取servletContext对象
        ServletContext context=config.getServletContext();
        String contextValue=context.getInitParameter("context");
        System.out.println("获取servletContext的配置参数："+contextValue);
    }

    //处理get请求的
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("接收到客户端传递进来的请求");
//        未解决中文乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        接收前端传递过来的参数
        String username=req.getParameter("username");
        String userpwd=req.getParameter("userpwd");
        System.out.println("前端传递的username："+username);
        System.out.println("前端传递的userpwd："+userpwd);
//调用业务逻辑处理层
        LoginService service=new LoginService();
        boolean ok=service.login(username,userpwd);
//        若ok为true，则表示用户名密码匹配，则直接跳转到登录成功页面
//        反之调回到登录页面
        if(ok){
//            页面转发
            req.getRequestDispatcher("layout.html").forward(req,resp);
        }else{
//            重定向
            resp.sendRedirect("login.jsp");
        }
    }
//处理post请求的
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);
    }
}
